import { defineStore } from "pinia";
import { computed, reactive, ref } from "vue";
import {
  FriendStatus,
  IFriendGroupByUser,
  IFriendGroupItem,
  IFriendListItem,
  IUpdateFriendGroupParams,
} from "@/types/friend.ts";
import { IGroupListItem, IGroupMember } from "@/types/group.ts";
import { GetJoinGroup } from "@/api/group";
import { RequestFriendList } from "@/api/friend";
import { ChatType, IMessage } from "@/types/chat";
import { GetUserFriendGroup } from "@/api/user";
import { IAiMessageListItem } from "@/types/ai";

export const useCache = defineStore(
  "cache",
  () => {
    //用户好友分组列表
    const FriendGroupCache = ref<IFriendGroupItem[] | null>(null);

    // 好友列表
    const FriendListCache = ref<IFriendListItem[] | null>(null);

    // 根据好友分配分组
    const FriendGroupByUserMapCache = computed(() => {
      // fix:要不要用worker实现合并
      const groupMap = new Map<number, IFriendGroupByUser>();
      FriendGroupCache.value?.forEach((friendGroup) => {
        groupMap.set(friendGroup.id, {
          id: friendGroup.id,
          name: friendGroup.name,
          isDefault: friendGroup?.isDefault || false,
          users: [],
        });
      });

      FriendListCache.value?.forEach((user) => {
        const group = groupMap.get(user.groupId);
        group?.users.push(user);
      });
      return Array.from(groupMap.values());
    });

    // 群列表
    const GroupListCache = ref<IGroupListItem[] | null>(null);

    // 群成员Map key->群id value->群成员
    const GroupMemberCache = reactive<Map<number, IGroupMember[]>>(new Map());

    // 消息缓存  key=>sessionId value=>消息列表
    let ChatMessageMapCache = reactive<Map<string, IMessage[]>>(new Map());

    // ai消息缓存 key=>sessionId value=>消息列表
    let AiMessageMapCache = reactive<Map<number, IAiMessageListItem[]>>(new Map());

    // 添加好友分组
    function AddFriendGroupMapCache(data: IFriendGroupItem) {
      if (!FriendGroupCache.value) FriendGroupCache.value = [];
      FriendGroupCache.value.push(data);
    }

    //更新好友分组名
    function UpdateFriendGroupCacheByName(params: IUpdateFriendGroupParams) {
      if (!FriendGroupCache.value) return;
      const group = FriendGroupCache.value.findIndex((item) => item.id === params.id);
      if (group === -1) return;
      FriendGroupCache.value[group].name = params.name;
    }

    // 更新好友的分组
    function UpdateFriendCacheByGroupId(friendId: number, groupId: number) {
      if (!FriendListCache.value) return;
      const index = FriendListCache.value?.findIndex((item) => item.id === friendId);
      if (index === -1) return;
      FriendListCache.value[index].groupId = groupId;
    }

    // 删除好友分组
    function DeleteFriendGroupCache(groupId: number, defaultGroupId: number) {
      if (!FriendListCache.value || !FriendGroupCache.value) return;
      FriendListCache.value = FriendListCache.value.map((friend) =>
        friend.groupId === groupId ? { ...friend, groupId: defaultGroupId } : friend,
      );
      FriendGroupCache.value = FriendGroupCache.value.filter((group) => group.id !== groupId);
    }

    // 查找好友 ->如果不存在 去拉取远程好友数据
    async function FindFriendListCache(message: IMessage) {
      if (message.chatType != ChatType.friend) return;
      const isNewFriend = FriendListCache.value?.some((friend) => friend.id === message.sendId);
      if (isNewFriend) return;
      await GetUserFriendList();
    }

    // 更新好友状态
    function UpdateFriendStatus(friendId: number, status: FriendStatus = FriendStatus.online) {
      if (!FriendListCache.value) return;
      let index = FriendListCache.value.findIndex((friend) => friend.id === friendId);
      if (index === -1) return;
      console.log("准备更新好友状态", friendId);
      FriendListCache.value[index].status = status;
    }

    // 查找群 ->如果不存在 拉取远程群数据
    async function FindGroupListCache(message: IMessage) {
      if (message.chatType != ChatType.group) return;
      const isNewGroup = GroupListCache.value?.some((friend) => friend.id === message.sendId);
      if (isNewGroup) return;
      await GetUserFriendList();
    }

    // 添加好友
    function AddFriendListCache(data: IFriendListItem) {
      if (!FriendListCache.value) FriendListCache.value = [];
      FriendListCache.value.push(data);
    }

    // 获取好友详情
    function GetFriendInfo(friendId: number): IFriendListItem | null {
      if (!FriendListCache.value) return null;
      let friendInfo = FriendListCache.value.find((friend) => friend.id === friendId);
      if (!friendInfo) return null;
      return friendInfo;
    }

    // 添加群
    function AddGroupListCache(data: IGroupListItem) {
      if (!GroupListCache.value) GroupListCache.value = [];
      GroupListCache.value.push(data);
    }

    // 获取群详情
    function GetGroupInfo(groupId: number): IGroupListItem | null {
      if (!GroupListCache.value) return null;
      let groupInfo = GroupListCache.value.find((group) => group.id === groupId);
      if (!groupInfo) return null;
      return groupInfo;
    }

    function UpdateGroupListByFiled(groupId: number, data: Partial<IGroupListItem>) {
      if (!GroupListCache.value) return;
      const index = GroupListCache.value?.findIndex((group) => group.id === groupId);
      if (index === -1) return;
      for (const key in data) {
        (GroupListCache.value[index][key as keyof IGroupListItem] as any) = data[key as keyof IGroupListItem];
      }
    }

    // 获取群成员信息
    function GetGroupMemberInfo(groupId: number, userId: number): IGroupMember | undefined {
      let member = GroupMemberCache.get(groupId);
      if (!member) return;
      let user = member.find((user) => user.id === userId);
      if (!user) return;
      return user;
    }

    // 拉取好友列表
    async function GetUserFriendList() {
      const res = await RequestFriendList();
      if (res?.status !== 200) return;
      FriendListCache.value = res.data;
    }

    // 拉取群列表
    async function GetUserJoinGroup() {
      let res = await GetJoinGroup();
      if (!res || res.status != 200) return;
      GroupListCache.value = res.data;
    }

    // 拉取好友分组
    async function GetUserFriendGroupList() {
      const res = await GetUserFriendGroup();
      if (res?.status !== 200) return;
      FriendGroupCache.value = res.data;
    }

    // 重置状态
    function ResetCacheState() {
      FriendGroupCache.value = null;
      FriendListCache.value = null;
      GroupListCache.value = null;
    }

    // 重置cache
    function ResetCache() {
      localStorage.removeItem("cache");
    }

    return {
      AiMessageMapCache,
      FriendGroupCache,
      FriendListCache,
      FriendGroupByUserMapCache,
      GroupListCache,
      GroupMemberCache,
      ChatMessageMapCache,
      AddFriendGroupMapCache,
      AddFriendListCache,
      AddGroupListCache,
      DeleteFriendGroupCache,
      UpdateFriendGroupCacheByName,
      UpdateFriendCacheByGroupId,
      UpdateGroupListByFiled,
      ResetCache,
      GetUserFriendList,
      GetUserJoinGroup,
      GetUserFriendGroupList,
      GetFriendInfo,
      GetGroupInfo,
      GetGroupMemberInfo,
      FindFriendListCache,
      FindGroupListCache,
      ResetCacheState,
      UpdateFriendStatus,
    };
  },
  {
    localStore: {
      store: true,
    },
  },
);
